const Koa = require('koa')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const mongoose = require('mongoose')
const path = require('path')
const app = new Koa()
const routerResponse = require('./middleware/routerResponse')
const routing = require('./routes')
const { connectionStr } = require('./config/config')

// 连接数据库
mongoose.connect(connectionStr,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify:false
    },
    (err) => {
        if (err) {
            console.log('数据库连接错误信息：', err)
        } else {
            console.log('数据库连接成功')
        }
    })
mongoose.connection.on('error', console.error);

// 配置统一请求头
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*')
    //用于判断request来自ajax还是传统请求
    ctx.set("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept, Authorization");
    //允许访问的方式
    ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    //内容类型：如果是post请求必须指定这个属性
    ctx.set('Content-Type', 'application/json;charset=utf-8')
    await next()
})

app.use(routerResponse())
app.use(koaStatic(path.join(__dirname, 'public')))

// 注册中间件
// 解析请求体,支持文件类型
app.use(koaBody({
    // 支持文件
    multipart:true,
    formidable:{
        uploadDir:path.join(__dirname, '/public/uploads'),
        keepExtensions:true
    }
}))
// 参数校验
app.use(parameter(app))

// 处理错误信息 区分生产环境与开发环境
app.use(error({
    postFormat: (e, {
        stack, ...rest
    }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
}))

// 批量注册路由
routing(app)

app.listen(3000, () => {
    console.log('服务启动成功')
})